<?php


namespace app\index\controller;


use app\index\common\Common;
use app\index\model\ActionRole;
use app\index\model\Country;
use app\index\model\CustomerDiscount;
use app\index\model\CustomerOrder;
use app\index\model\CustomerTrackRecord;
use app\index\model\Order;
use app\index\model\Customer;
use app\index\model\OrderHistory;
use app\index\model\OrderItem;
use app\index\model\OrderItemDetail;
use app\index\model\OrderPayment;
use app\index\model\Product;
use app\index\model\ProductPurHistory;
use app\index\model\User;
use app\index\model\Waybill;
use RuntimeException;
use think\Db;
use think\Exception;
use think\Loader;
use think\Request;
use think\response\Json;

class OrderController extends BaseController
{
    protected $request;
    protected $validate;

    protected $type=['1'=>'PC','2'=>'KG'];

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->request=$request;
        $this->validate=Loader::validate('Order');
    }

    /**
     * getCustomerOrderParam
     * 获取已订商品页面配置
     * @url /ordered/param
     * @method POST
     * @request int status
     * @return Json
     * @author Asira
     * @date 2020/12/28
     */
    public function getCustomerOrderParam(): Json
    {
        $post=input('post.',[],'trim');
        $search_param=[
            'status'=>$post['order_status']??null,
            'create_user'=>$post['create_user']??null,
            'search_key'=>$post['search_key']??null,
            'search_value'=>$post['search_value']??null,
            'group_id'=>$post['group_id']??null,
        ];
        $customer_list=CustomerOrder::getCustomerList($search_param);
        $country_list=Country::getCountryList();
        ['user_list'=>$user_list,'group_list'=>$group_list]=User::getUserList();

        return json(['code'=>0,'customer_list'=>$customer_list,'country'=>$country_list,'user'=>$user_list,'group'=>$group_list]);
    }

    /**
     * getCustomerOrderList
     * 获取已订商品列表
     * @url /ordered/list
     * @method Post
     * @request 页码 pageIndex int
     * @request 页面大小 pageSize int
     * @request 搜索名 search_key string
     * @request 搜索值 search_value string
     * @request 客户名称 customer_name string
     * @request 订单状态 status string
     * @request 创建时间 create_time string
     * @return Json
     * @author Asira
     * @date 2020/12/28
     */
    public function getCustomerOrderList(): Json
    {
        $page=input('post.pageIndex',1);
        $size=input('post.pageSize',10);
        $post=input('post.',[],'trim');
        $search_param=[
            'search_key'=>$post['search_key']??null,
            'search_value'=>$post['search_value']??null,
            'customer_name'=>$post['customer_name']??null,
            'create_user'=>$post['create_user']??null,
            'status'=>$post['order_status']??null,
            'create_time'=>$post['create_time']??null,
            'group_id'=>$post['group_id']??null,
            'selling_price'=>$post['selling_price']??null,
        ];
        $page_param=[
            'page_num'=>$page,
            'page_size'=>$size,
        ];
        ['status'=>$status,'result'=>$result]=CustomerOrder::getList($search_param,$page_param);
        if($status===false){
            return json(['code'=>1,'msg'=>$result['msg']]);
        }
        return json(['code'=>0,'order'=>$result['order'],'pageTotal'=>$result['total'],'action_role'=>$result['action_role']]);
    }

    public function getCustomerOrderById(){
        $id=input('post.id');
        if(!$id){
            return json(['code'=>1,'msg'=>'id不能为空']);
        }
        ['status'=>$status,'result'=>$result]=CustomerOrder::getCustomerOrderById($id);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        $data=$result['data'];
        $detail=$result['detail'];
        $product[]=['label'=>$data['cn_name'],'value'=>$data['pro_id']];
        $customer[]=['label'=>$data['customer_name'],'value'=>$data['customer_name']];
        return json(['code'=>0,'data'=>$data,'detail'=>$detail,'product'=>$product,'customer'=>$customer]);
    }

    public static function generateOrderId($num=0): string
    {
        $count=Order::where('create_time','>=',date('Y-m-d').' 00:00:00')->count();
        if($count===null){
            $count=0;
        }
        $id=date('ymd').'0000';
        $order_id=$count+$num+1;
        $max_id_len=strlen($order_id);

        $id_len=strlen($id);
        if($max_id_len>4){
            $max_id_len=4;
        }
        return substr($id,0,$id_len-$max_id_len).($order_id);
    }

    public static function createByCustomerOrder($customer_orders,$customer_orders_detail): array
    {
        $order=[];
        $order_item=[];
        $order_id=self::generateOrderId();
        foreach ($customer_orders as $key=>$value){
            if($key===0) {
                $order=[
                    'order_id'=>$order_id,
                    'customer_id'=>$value['customer_id'],
                    'user_name'=>$value['customer_name'],
                    'items_price'=>0,
                    'ship_fee'=>0,
                    'total_price'=>0,
                    'curr_type'=>0,
                    'country'=>$value['country'],
                    'city'=>$value['city'],
                    'address'=>$value['address'],
                    'zip_code'=>$value['zip_code'],
                    'phone'=>$value['phone'],
                    'email'=>$value['email'],
                    'create_user'=>$value['create_user'],
                    'create_group'=>$value['create_group'],
                ];
            }
            $order['items_price']+=$value['selling_price'];
            $order_item[]=[
                'detail'=>$customer_orders_detail[$value['id']]??[],
                'demand_stock'=>$value['demand_stock'],
                'cn_name'=>$value['cn_name'],
                'en_name'=>$value['en_name'],
                'amount'=>$value['amount'],
                'type'=>$value['pro_type'],
                'selling_price'=>$value['selling_price'],
                'pur_price'=>$value['pur_price'],
                'pro_id'=>$value['pro_id'],
                'create_user'=>$value['create_user'],
                'create_group'=>$value['create_group'],
                'remark'=>$value['remark']??'',
                'gift'=>$value['gift'],
            ];
        }

        return ['status'=>true,'result'=>['order'=>$order,'order_item'=>$order_item]];
    }

    public static function checkCustomerOrder($ids): array
    {
        $self=new self();
        ['status'=>$status,'result'=>$result]=CustomerOrder::getCustomerOrderByIds($ids);
        if($status===false){
            return ['status'=>false,'result'=>$result];
        }
        $customer_orders=$result['data'];
        $customer_orders_detail=$result['detail'];
        $customer=0;
        $customer_value=0;
        $ship_fee_check=1;
        foreach ($customer_orders as $key=>$value){
            if($key===0) {
                $customer = $value['customer_id'];
                $ship_fee_check=$value['ship_fee_check'];
                $customer_value=$value;
            }else if($customer!==$value['customer_id']){
                return ['status'=>false,'result'=>'不能选择两个客户'];
            }
        }
        $validate_result = $self->validate->scene('customer_order')->check($customer_value);
        if (!$validate_result) {
            return ['status' => false, 'result' => $customer_value['customer_name'] . '用户信息不完整，' . $self->validate->getError()];
        }
        return ['status'=>true,'result'=>['customer'=>$customer,'customer_orders'=>$customer_orders,'customer_orders_detail'=>$customer_orders_detail,'ship_fee_check'=>$ship_fee_check]];
    }

    public function previewCreateOrder(){
        $id=input('post.ids/a');
        $CustomerOrderClass=new CustomerOrder();
        $customer_order_data=$CustomerOrderClass->where('id','in',$id)->field('sum(selling_price) price,customer_name')->group('customer_name')->select()->toArray();
        if(count($customer_order_data)>=2){
            return json(['code'=>1,'msg'=>'请选择同一个客户']);
        }
        if(empty($customer_order_data)){
            return json(['code'=>1,'msg'=>'请选择要创建的数据']);
        }
        $customer_order_data=$customer_order_data[0];

        $discount_price=CustomerDiscount::where('customer_id','=',$customer_order_data['customer_name'])->value('ifnull(balance,0) balance');
        if(empty($discount_price)){
            $discount_price=0;
        }
        $ship_fee_check=Customer::where('id','=',$customer_order_data['customer_name'])->value('ship_fee');

        $where['customer_id']=['=',$customer_order_data['customer_name']];
        $where['pay_type']=['in',[0,1,2,3]];
        $where['order_status']=['=',1];
        $where['del_flag']=['=',0];
        $old_order = Order::where($where)->field('id,order_id,items_price,total_price,pay_type,amount_discount,ship_fee')->select()->toArray();

        $preview_order_data=['item_price'=>round($customer_order_data['price'],2)];

        if(empty($old_order)){
            $preview_order_data['type']=1;
            $price=$customer_order_data['price'];
        }else{
            foreach ($old_order as $key=>$value){
                if($key===0){
                    $preview_order_data['merge_order_id']=$value['id'];
                    $old_order[$key]['check']=true;
                }else{
                    $old_order[$key]['check']=false;
                }
                $old_order[$key]['pay_type_text']=Order::$pay_type_list[$value['pay_type']];
            }
            $preview_order_data['type']=2;
            $price=round($customer_order_data['price']+$old_order[0]['items_price'],2);
            $preview_order_data['item_price']=$price;

        }

        if($ship_fee_check){
            $preview_order_data['shipping_fee_check']=true;
            $preview_order_data['shipping_fee']=0;//Common::getShippingPrice($price);
        }else{
            $preview_order_data['shipping_fee_check']=false;
            $preview_order_data['shipping_fee']=0;
        }

        $preview_order_data['discount_check']=true;
        $total_price=round($preview_order_data['item_price']+$preview_order_data['shipping_fee'],2);
        if($discount_price>=$total_price){
            $preview_order_data['amount_discount']=round($discount_price-0.01,2);
        }else{
            $preview_order_data['amount_discount']=$discount_price;
        }
        $preview_order_data['total_price']=round($total_price-$preview_order_data['amount_discount'],2);
        return json(['code'=>0,'customer_order'=>$customer_order_data,'order'=>$old_order,'discount_price'=>$discount_price,'preview_order_data'=>$preview_order_data]);
    }

    /**
     * createOrder
     *  已订商品创建订单
     * @url /ordered/create
     * @method POST
     * @request array ids 选择的id
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author Asira
     * @date 2021/2/1
     */
    public function createOrder(): Json{
        $ids=input('post.ids/a',[]);
        $create=input('post.create',0);
        $preview_order=input('post.preview_order/a');
        if(empty($ids)){
            return json(['code'=>1,'msg'=>'请选择要创建的商品']);
        }
        ['status'=>$status,'result'=>$result]=self::checkCustomerOrder($ids);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        $customer=$result['customer'];
        $customer_orders=$result['customer_orders'];
        $customer_orders_detail=$result['customer_orders_detail'];
        $ship_fee_check=$result['ship_fee_check'];
        if($create===0) {
            ['search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('order');
            if(!empty($search_user)){
                $where['create_user']=['in',$search_user];
            }
            if(!empty($group)){
                $where['create_group']=['=',$group];
            }
            $where['customer_id']=['=',$customer];
            $where['pay_type']=['<>',4];
            $where['order_status']=['=',1];
            $where['del_flag']=['=',0];
            $old_order = Order::where($where)->field('id,order_id,total_price,user_name,pay_type')->select()->toArray();
            if (!empty($old_order)) {
                foreach ($old_order as $key=>$value){
                    $old_order[$key]['pay_type_text']=Order::$pay_type_list[$value['pay_type']];
                }
                return json(['code' => 2, 'msg' => '请选择要合并的订单', 'order' => $old_order]);
            }
        }
        ['status'=>$status,'result'=>$result]=self::createByCustomerOrder($customer_orders,$customer_orders_detail);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        ['order'=>$order,'order_item'=>$order_item]=$result;


        if (isset($preview_order['shipping_fee'])) {
            $order['ship_fee'] = $preview_order['shipping_fee'];
        }/* else if($ship_fee_check===1) {
            $order['ship_fee'] = Common::getShippingPrice($order['items_price']);
        }*/else{
            $order['ship_fee']=0;
        }

        if(isset($preview_order['amount_discount'])){
            $order['amount_discount']=$preview_order['amount_discount'];
        }else {
            $order['amount_discount'] = 0;
        }

        $order['total_price'] =$order['items_price']+ $order['ship_fee'];
        if(round($order['total_price']-$order['amount_discount'],2)<0.01){
            return json(['code'=>1,'msg'=>'不能使一个账单金额低于0.01']);
        }
        ['status'=>$status,'result'=>$result]=Order::createOrder($order,$order_item,$ids);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        $order_id=$result['id'];
        ['status'=>$status,'result'=>$result]=Order::sentInvoice($order_id);
        if($status===false){
            return json(['code'=>1,'msg'=>'创建账单成功,发送账单失败.'.$result]);
        }
        return json(['code'=>0,'msg'=>'创建账单成功']);
    }

    /**
     * createOrderMerge
     * 已订商品合并到旧账单
     * @url /ordered/merge/create
     * @method POST
     * @request array ids 选择的已订商品
     * @request order_id 要合并到的订单
     * @return Json
     * @author Asira
     * @date 2021/2/2
     */
    public function createOrderMerge(): Json
    {
        $ids=input('post.ids/a',[]);
        $order_id=input('post.order_id');
        $preview_order=input('post.preview_order/a');
        if(empty($ids)){
            return json(['code'=>1,'msg'=>'请选择要创建的商品']);
        }
        if(empty($order_id)){
            return json(['code'=>1,'msg'=>'请选择要合并到的订单']);
        }
        ['status'=>$status,'result'=>$result]=self::checkCustomerOrder($ids);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        $customer_orders=$result['customer_orders'];
        $customer_orders_detail=$result['customer_orders_detail'];
        $ship_fee_check=$result['ship_fee_check'];
        $order=Order::getOrderById($order_id);
        $order_show_index=OrderItem::where('order_id','=',$order_id)->where('del_flag','=',0)->max('show_index');
        if (empty($order)) {
            return json(['code' => 1, 'msg' => '未找到订单']);
        }
        if ($order['pay_type']===4) {
            return json(['code' => 1, 'msg' => '订单已付款']);
        }
        $order_items = [];
        $order_items_detail=[];
        $update_order=['items_price'=>$order['items_price'],'customer_id'=>$order['customer_id'],'old_discount'=>$order['amount_discount'],'create_user'=>$order['create_user']];
        foreach ($customer_orders as $value) {
            $order_show_index++;
            if($value['gift'] === 1){
                $value['gift'] = 2;
            }
            $order_items[] = [
                'order_id' => $order_id,
                'show_index' => $order_show_index,
                'pro_id' => $value['pro_id'],
                'cn_name' => $value['cn_name'],
                'en_name' => $value['en_name'],
                'remark' => $value['remark'],
                'pur_price' => $value['pur_price'],
                'amount' => $value['amount'],
                'type' => $value['pro_type'],
                'selling_price' => $value['selling_price'],
                'create_user' => $value['create_user'],
                'create_group'=>$value['create_group'],
                'gift'=>$value['gift']
            ];
            $order_items_detail[]=$customer_orders_detail[$value['id']]??[];
            $update_order['items_price']+=$value['selling_price'];
        }
        if(isset($preview_order['shipping_fee'])){
            $update_order['ship_fee']=$preview_order['shipping_fee'];
        }/*elseif($ship_fee_check) {
            $update_order['ship_fee'] = Common::getShippingPrice($update_order['items_price']);
        }*/else{
            $update_order['ship_fee']=0;
        }
        if(isset($preview_order['amount_discount'])){
            $update_order['amount_discount']=$preview_order['amount_discount'];
        }else {
            $update_order['amount_discount'] = 0;
        }

        $update_order['total_price']=round($update_order['items_price']+$update_order['ship_fee'],2);
        ['status'=>$status,'result'=>$result]=Order::createOrderMerge($ids,$order_id,$update_order,$order_items,$order_items_detail);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function getOrderParam(){
        $customer_list=Customer::getList();
        $pay_type_list=Order::$pay_type_list;
        $country=Country::getCountryList();
        $logistics_status_list=Order::$logistics_status_list;
        $track_type=CustomerTrackRecord::$track_type;
        ['user_list'=>$user_list,'group_list'=>$group_list]=User::getUserList();
        return json(['code'=>0,'customer'=>$customer_list,'pay_type'=>$pay_type_list,'logistics_status'=>$logistics_status_list,'user_list'=>$user_list,'group_list'=>$group_list,'country_list'=>$country,'track_type'=>$track_type]);
    }

    public function getOrderList(){
        $page=input('post.pageIndex',1);
        $size=input('post.pageSize',10);
        $post=input('post.',[],'trim');
        $search_param=[
            'search_key'=>$post['search_key']??null,
            'search_value'=>$post['search_value']??null,
            'customer_id'=>$post['customer_id']??null,
            'create_time'=>$post['create_time']??null,
            'payment_time'=>$post['payment_time']??null,
            'track'=>$post['track']??null,
            'pay_type'=>$post['pay_type']??null,
            'logistics_status'=>$post['logistics_status']??null,
            'group_id'=>$post['group_id']??null,
            'user_id'=>$post['user_id']??null,
            'selling_price'=>$post['selling_price']??null,
        ];
        $page_param=[
            'page_num'=>$page,
            'page_size'=>$size,
        ];
        ['status'=>$status,'result'=>$result]=Order::getList($search_param,$page_param);
        if($status===false){
            return json(['code'=>1,'msg'=>$result['msg']]);
        }
        return json(['code'=>0,'order'=>$result['order'],'pageTotal'=>$result['total'],'action_role'=>$result['action_role']]);
    }

    public function cancelOrder(){
        $id=input('post.id');
        if(!$id){
            return json(['code'=>1,'msg'=>'id不能为空']);
        }

        ['status'=>$status,'result'=>$result]=Order::cancelOrder($id);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        ['status'=>$status,'result'=>$result]=Product::demandStockByProduct($result);
        if($status===false){
            return json(['code'=>2,'msg'=>'更新成功，锁定需求库存失败'.$result]);
        }
        return json(['code'=>0,'msg'=>'取消成功']);
    }

    /**
     * getOrderItemsById
     * 根据ID获取账单详情
     * @url /order/items/id
     * @method POST
     * @request int id 账单ID
     * @return Json
     * @author Asira
     * @date 2021/1/15
     */
    public function getOrderItemsById(): Json
    {
        $id=input('post.id');
        if(!$id){
            return json(['code'=>1,'msg'=>'id不能为空']);
        }
        $items=OrderItem::getOrderItemsById($id);
        $items_detail=OrderItemDetail::getOrderItemDetailByOrderId($id);
        $order=Order::getOrderById($id,0);
        $history=OrderHistory::getOrderHistoryById($id);

        $country_list=Country::getCountryList();
        if(empty($items) || empty($order)){
            return json(['code'=>1,'msg'=>'未找到订单信息']);
        }
        $keys=0;
        foreach ($items as $key=>$value){
            $value['cn_desc']='PC';//$this->type[$value['type']];
            $value['keys']=$keys;
            $value['delete']=false;
            if ($value['lock_status']==1){
                $value['lock_status_text']='是';
            }else{
                $value['lock_status_text']='否';
            }
            $keys++;
            if(isset($items_detail[$value['id']])){
                foreach ($items_detail[$value['id']] as $i=>$item){
                    $item['delete']=false;
                    $item['keys']=$keys;
                    if($items_detail[$value['id']][$i]['lock_status']==1){
                        $item['lock_status_text']='是';
                    }else{
                        $item['lock_status_text']='否';
                    }
                    $items_detail[$value['id']][$i]=$item;
                    $keys++;
                }
                $value['children']=$items_detail[$value['id']];
            }
            $items[$key]=$value;
        }
        $order['items_keys']=$keys;
        if($order['stock_status']===2){
            $product_history=ProductPurHistory::getStockHistoryByOrderId($id);
            if(!empty($product_history)){
                $product_history_list=[];
                foreach ($product_history as $key=>$value){
                    $value['amount_text']=$value['amount'].Product::$product_type[$value['type']];
                    $product_history_list[$value['order_item_id']][]=$value;
                }
                foreach ($items as $key=>$value){
                    if(isset($product_history_list[$value['id']])){
                        $items[$key]['history_children']=$product_history_list[$value['id']];
                    }
                }
            }
        }
        $pay_status['text']=Order::$pay_type_list[$order['pay_type']];
        if(in_array($order['pay_type'],[0,1],true)){
            $pay_status['type']='info';
        }elseif(in_array($order['pay_type'],[2,3],true)){
            $pay_status['type']='';
        }elseif($order['pay_type'] === 4){
            $pay_status['type']='success';
        }elseif($order['pay_type'] === 5){
            $pay_status['type']='warning';
        }elseif(in_array($order['pay_type'],[6,7],true)){
            $pay_status['type']='danger';
        }

        $order['curr']='USD';
        $order['real_price']=round($order['total_price']-$order['amount_discount'],2);
        if($order['cc_email']) {
            $order['cc_email'] = explode(',', $order['cc_email']);
        }else{
            $order['cc_email']=[];
        }
        return json(['code'=>0,'order'=>$order,'items'=>$items,'history'=>$history,'pay_status'=>$pay_status,'country_list'=>$country_list]);
    }

    public function mergeOrder(){
        $ids=input('post.ids/a');
        if(empty($ids)){
            return json(['code'=>1,'msg'=>'请选择要合并的订单']);
        }
        if(count($ids)<2){
            return json(['code'=>1,'msg'=>'最少选择两个订单']);
        }
        $OrderClass=new Order();
        $OrderItemClass=new OrderItem();
        $OrderHistoryClass=new OrderHistory();
        $customer_num=[];
        $pay_num=0;
        $order=$OrderClass::getOrderByIds($ids);
        if(count($order)<2){
            return json(['code'=>1,'msg'=>'可合并订单数量不足2']);
        }
        $new_order=[];
        $order_ids=[];
        $logistics_status=1;
        foreach ($order as $key=>$value){
            if($value['logistics_status']===0){
                $logistics_status=0;
            }
            $customer_num[]=$value['customer_id'];
            $order_ids[]=$value['id'];
            if($value['pay_type']===3) {
                $pay_num++;
            }
            if($key===0 || $value['pay_type']===3){
                $new_order = $value;
            }
        }
        $new_order['logistics_status']=$logistics_status;
        $customer_num=array_unique($customer_num);
        if(count($customer_num)>1){
            return json(['code'=>1,'msg'=>'选择的订单不是同一个客户']);
        }
        if($pay_num>1){
            return json(['code'=>1,'msg'=>'不能合并两个已付款的订单']);
        }
        $items=$OrderItemClass::getOrderItemsByIds($order_ids);
        $order_items=[];
        $show_index=1;
        foreach ($items as $value){
            if($new_order['id']===$value['order_id'] && $value['show_index']>$show_index){
                $show_index=$value['show_index'];
            }
            $order_items[$value['order_id']][]=$value;
        }

        $delete_invoice=[];
        $cancel_invoice=[];
        $cancel_order=[];
        $order_history=[];
        $order_history[]=['order_id'=>$new_order['id'],'operator'=>$this->user_session['id'],'operational'=>'合并订单'];
        $insert_new_order_items=[];
        $items_price=$new_order['items_price'];
        $ship_fee=$new_order['ship_fee'];
        $amount_discount=0;
        foreach ($order as $key=>$value){
            if($new_order['id']!==$value['id']){
                $items_price+=$value['items_price'];
                $amount_discount+=$value['amount_discount'];
                $ship_fee+=$value['ship_fee'];
                foreach ($order_items[$value['id']] as $item){
                    $show_index++;
                    $item['order_id']=$new_order['id'];
                    $item['show_index']=$show_index;
                    $insert_new_order_items[]=$item;
                }
                $order_history[]=['order_id'=>$value['id'],'operator'=>$this->user_session['id'],'operational'=>'被合并订单'];
                $cancel_order[]=$value['id'];
                if ($value['pay_type'] === 2) {
                    $cancel_invoice[] = ['receipt_number'=>$value['receipt_number'],'group'=>$value['create_group']];
                } else if ($value['pay_type'] === 1) {
                    $delete_invoice[] = ['receipt_number'=>$value['receipt_number'],'group'=>$value['create_group']];
                }
            }
        }
        $new_order['items_price']=$items_price;
        $new_order['amount_discount']=$amount_discount;
//        $ship_fee=Common::getShippingPrice($items_price);
        $new_order['total_price']=round($items_price+$ship_fee,2);
        $new_order['ship_fee']=$ship_fee;

        $OrderClass->startTrans();

        try{
            $result=$OrderClass->where('id',$new_order['id'])->update($new_order);
            if($result===false){
                return ['code'=>1,'msg'=>'更新订单失败'];
            }
            $result=$OrderClass->where('id','in',$cancel_order)->update(['order_status'=>2,'pay_type'=>5]);
            if($result===false){
                return ['code'=>1,'msg'=>'取消旧订单失败'];
            }
            $result=$OrderItemClass->saveAll($insert_new_order_items);
            if($result===false){
                return ['code'=>1,'msg'=>'合并商品失败'];
            }
            $result=$OrderHistoryClass->saveAll($order_history);
            if($result===false){
                return ['code'=>1,'msg'=>'保存订单历史记录失败'];
            }
            if($new_order['pay_type']!==0) {
                $order = $OrderClass::getOrderById($new_order['id']);
                $items = $OrderItemClass::getOrderItemsById($new_order['id']);
                $order['items'] = $items;

                ['status' => $status, 'result' => $result] = PaypalApi::updateInvoice($order);
                if($status===false){
                    return json(['code'=>1,'msg'=>$result]);
                }
            }
            if(!empty($cancel_invoice)){
                foreach ($cancel_invoice as $value){
                    ['status'=>$status,'result'=>$result]=PaypalApi::cancelInvoice($value['receipt_number'],$value['group']);
                    if($status===false){
                        return json(['code'=>1,'msg'=>$result]);
                    }
                }
            }
            if(!empty($delete_invoice)){
                foreach ($delete_invoice as $value){
                    ['status'=>$status,'result'=>$result]=PaypalApi::deleteInvoice($value['receipt_number'],$value['group']);
                    if($status===false){
                        return json(['code'=>1,'msg'=>$result]);
                    }
                }
            }
            $OrderClass->commit();
            return json(['code' => 0, 'msg' => '合并成功']);
        }catch (\Exception $e){
            $OrderClass->rollback();
            trace($e->getMessage(), 'error');
            return json(['code'=>1,'msg'=>'合并失败']);
        }
    }

    public function createInvoice(){
        $id=input('post.id');
        return $this->invoiceCreate($id);
    }

/*    public function batchCreateInvoice(){
        $ids=input('post.ids');
        dump($ids);
        die();
        return $this->invoiceCreate($ids);
    }*/

    /**
     * invoiceCreate
     * 创建账单
     * @url
     * @method
     * @param $id
     * @return Json
     * @author Asira
     * @date 2021/1/13
     */
    public function invoiceCreate($id): Json
    {
        $order=Order::getOrderById($id);
        if(empty($order)){
            return json(['code'=>1,'msg'=>'未找到订单']);
        }
        $items=OrderItem::getOrderItemsById($id);
        $order['items']=$items;
        ['status'=>$status,'result'=>$result]=PaypalApi::createInvoice($order);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        $invoice_id=$result['id'];
        ['status'=>$status,'result'=>$result]=PaypalApi::sentInvoice($invoice_id,$order['create_group']);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
//        $status=$result['status'];
        ['status'=>$status,'result'=>$result]=Order::crateInvoice($id,$invoice_id,$order['total_price']);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }

        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    /**
     * updateOrderWithCreate
     * 更新账单
     * @url /order/invoice/save
     * @method POST
     * @return Json
     * @author Asira
     * @date 2021/2/2
     */
    public function updateOrderWithCreate(): Json
    {
        $id=input('post.id');
        $data=input('post.data/a');
        $items=input('post.items/a');
        $create=input('post.create');

        $update_order=['partial_pay'=>$data['partial_pay'],'pay_type'=>$data['pay_type'],'payment_type'=>$data['payment_type'],'ship_fee'=>$data['ship_fee'],'tip'=>$data['tip'],'amount_discount'=>$data['amount_discount'],'email'=>$data['email'],'user_name'=>$data['user_name'],'cc_email'=>null,'country'=>$data['country'],'phone'=>$data['phone'],'city'=>$data['city'],'address'=>$data['address'],'zip_code'=>$data['zip_code']];

        if(!empty($data['cc_email'])){
            $cc_email=[];
            foreach ($data['cc_email'] as $key=>$value){
                if($value) {
                    $cc_email[] = $value;
                }
            }
            if(!empty($cc_email)) {
                $update_order['cc_email'] = implode(',', $cc_email);
            }
        }

/*        ['status'=>$status,'result'=>$result]=Order::updateOrderCheckData($id);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        $old_order=$result['order'];*/
//        $order_item_detail=OrderItemDetail::getOrderItemDetailByOrderId($id);

        $insert_items=[];
        $insert_items_detail=[];
        $update_items=[];
        $update_items_detail=[];
        $gift_item=[];
        $gift_item_detail=[];
        $update_gift=[];
        $update_gift_detail=[];
        $delete_gift=[];
        $delete_items=[];
        $pro_ids=[];
        $items_price=0;
        foreach ($items as $key=>$value){
            unset($value['keys']);
            if($value['delete']===true){
                if ($value['gift'] != 1) {
                    $delete_items[] = $value['id'];
                }else{
                    $delete_gift[] = $value['id'];
                }
                continue;
            }
            if($value['pro_id']) {
                $pro_ids[] = $value['pro_id'];
            }else{
                if(isset($value['children'])) {
                    foreach ($value['children'] as $i => $item) {
                        if ($item['pro_id']) {
                            $pro_ids[] = $item['pro_id'];
                        } else {
                            return json(['code' => 1, 'msg' => '详细信息商品不能为不存在商品']);
                        }
                    }
                }
            }
            if (!$value['id']) {
                if ($value['gift'] != 1) {
                    $insert_items[] = [
                        'order_id' => $id,
                        'cn_name' => $value['cn_name'],
                        'en_name' => $value['en_name'],
                        'show_index' => $key + 1,
                        'pro_id' => $value['pro_id'],
                        'amount' => $value['amount'],
                        'selling_price' => $value['selling_price'],
                        'type' => $value['type'],
                        'gift' => $value['gift'],
                        'remark'=>$value['remark'],
                        'create_user' => $value['create_user'] ?? $this->user_session['id'],
                        'create_group' => $value['create_group'] ?? $this->user_session['group_id']
                    ];
                    $insert_items_detail[]=$value['children']??[];

                    $items_price += (float)$value['selling_price'];
                } else {
                    $gift_item[] = ['order_id' => $id, 'cn_name' => $value['cn_name'], 'en_name' => $value['en_name'], 'show_index' => $key + 1, 'pro_id' => $value['pro_id'], 'amount' => $value['amount'], 'selling_price' => 0, 'type' => $value['type'], 'gift' => $value['gift'],'remark'=>$value['remark'], 'create_user' => $value['create_user']??$this->user_session['id'], 'create_group' => $value['create_group'] ?? $this->user_session['group_id']];
                    $gift_item_detail[]=$value['children']??[];
                }
            } else {
                $update_arr = ['id' => $value['id'],'pro_id' => $value['pro_id'],'cn_name' => $value['cn_name'], 'en_name' => $value['en_name'], 'amount' => $value['amount'],'remark'=>$value['remark'], 'selling_price' => $value['selling_price'],'type' => $value['type'], 'show_index' => $key + 1];
                if ($value['gift'] != 1) {
                    $update_items[] = $update_arr;
                    $update_items_detail[] = $value['children']??[];
                    $items_price += (float)$value['selling_price'];
                } else {
                    $update_gift[] = $update_arr;
                    $update_gift_detail[] = $value['children']??[];
                }
            }
        }

        $update_order['total_price']=$items_price+(float)$data['ship_fee'];
        $update_order['items_price']=$items_price;

        $sql_data=[$insert_items,$insert_items_detail,$update_items,$update_items_detail,$gift_item,$gift_item_detail,$update_gift,$update_gift_detail,$delete_items,$delete_gift];
        ['status'=>$status,'result'=>$result]=Order::updateOrderWithInvoice($id,$update_order,$sql_data,$pro_ids);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        ['status'=>$status,'result'=>$StockResult]=Product::demandStockByProduct($pro_ids);
        if($status===false){
            return json(['code'=>2,'msg'=>'更新成功，锁定需求库存失败'.$StockResult]);
        }
        $old_order=$result['old_order'];
        if($old_order['pay_type']===4){
            ['status'=>$status,'result'=>$StockResult]=Product::lockStockByOrder($id);
            if($status===false){
                return json(['code'=>2,'msg'=>'更新成功，锁定库存失败'.$StockResult]);
            }
        }
        if($old_order['pay_type']===0){
            return $this->invoiceCreate($id);
        }
        if($result['check']===false){
            return json(['code'=>0,'msg'=>$result['msg']]);
        }
        if(in_array($old_order['pay_type'], [1, 2, 3], true)){
            return $this->invoiceUpdate($id);
        }
        throw new RuntimeException('order data error');
    }

    public function updateInvoice(){
        $id=input('post.id');
        return $this->invoiceUpdate($id);
    }

    public function invoiceUpdate($id){
        ['status'=>$status,'result'=>$result]=Order::updateInvoice($id);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function sentInvoice(){
        $id=input('post.id');
        ['search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('order');
        if(!empty($group)){
            $where['create_group']=['=',$group];
        }
        if(!empty($search_user)) {
            $where['create_user'] = ['in', $search_user];
        }
        $where['id']=['=',$id];
        $order=Order::where($where)->field('create_group,receipt_number')->find();
        if(empty($order)){
            return json(['code'=>1,'msg'=>'未找到发票号']);
        }
        ['status'=>$status,'result'=>$result]=PaypalApi::sentInvoice($order['receipt_number'],$order['create_group']);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        ['status'=>$status,'result'=>$result]=Order::sentInvoice($id);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    /**
     * getPaymentById
     * 获取订单付款金额信息
     * @url payment/id
     * @method POST
     * @request int id 订单id
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author Asira
     * @date 2021/1/5
     */
    public function getPaymentById(): Json
    {
        $id=input('post.id');
        $data=Order::getPaymentById($id);
        $pay_way_list=OrderPayment::$pay_way_list;
        if(empty($data)){
            return json(['code'=>1,'msg'=>'未找到符合条件的账单']);
        }
        /*if($data['type']!==0){
            if($data['amount_discount']==0){
                $data['amount_discount']=round($data['total_price']*0.02,2);
            }
        }*/
        $data['pay']=round($data['total_price']-$data['amount_paid']-$data['amount_discount'],2);
        $data['pay_way']=0;
        $data['payment_date']=date('Y-m-d H:i:s');
        $data['note']='';
        return json(['code'=>0,'data'=>$data,'pay_way_list'=>$pay_way_list]);
    }

    /**
     * recordPayment
     * 账单付款
     * @url invoice/payment
     * @method POST
     * @request int id 订单id
     * @request float pay 支付金额
     * @request int pay_way 支付方式
     * @request string payment_date 支付时间
     * @request string note 备注
     * @author Asira
     * @date 2021/1/5
     */
    public function recordPayment(): Json
    {
        $id=input('post.id');
        $pay=input('post.pay');
        $pay_way=input('post.pay_way');
        $payment_date=input('post.payment_date');
        $amount_discount=input('post.amount_discount');
        $note=input('post.note');
        $payment_id=input('post.payment_id');
        $member_id=input('post.member_id');
        $type=input('post.type');
        $customer_id=input('post.customer_id');
        if (!$type){
            return json(['code'=>1,'msg'=>'请选择付款方式']);
        }
        if ($type==1){
            $payment=['order_id'=>$id,'payment_date'=>$payment_date,'invoice_payment_id'=>$payment_id,'method'=>OrderPayment::$pay_way_list[$pay_way],'amount'=>$pay,'note'=>$note,'amount_discount'=>$amount_discount,'create_user'=>$this->user_session['id']];
            $validate_result=$this->validate->scene('order_pay')->check($payment);

            if(!$validate_result){
                return json(['code'=>1,'msg'=>$this->validate->getError()],200);
            }
            ['status'=>$status,'result'=>$result]=OrderPayment::recordPayment($payment);
            if($status===false){
                return json(['code'=>1,'msg'=>$result]);
            }
        }else{
            $payment=['order_id'=>$id,'payment_date'=>$payment_date,'member_id'=>$member_id,'method'=>OrderPayment::$pay_way_list[$pay_way],'amount'=>$pay,'note'=>$note,'amount_discount'=>$amount_discount,'create_user'=>$this->user_session['id']];
            $validate_result=$this->validate->scene('order_pay_byCardId')->check($payment);

            if(!$validate_result){
                return json(['code'=>1,'msg'=>$this->validate->getError()],200);
            }
            ['status'=>$status,'result'=>$result]=OrderPayment::recordPaymentByCardId($payment,$customer_id);
            if($status===false){
                return json(['code'=>1,'msg'=>$result]);
            }
        }
        $pay_type=$result['pay_type'];
        if($pay_type===4) {
            ['status' => $status, 'result' => $result] = Product::lockStockByOrder($id);
            if($status===false){
                return json(['code'=>2,'msg'=>'付款成功.订单锁定库存失败 '.$result]);
            }
        }
        return json(['code'=>0,'msg'=>'付款成功']);
    }

    /**
     * ship
     * 修改账单状态为发货
     * @url /order/ship
     * @method POST
     * @request int id 账单ID
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author Asira
     * @date 2021/1/13
     */
    public function ship(): Json
    {
        $id=input('post.id');
        $OrderClass=new Order();
        $OrderHistoryClass=new OrderHistory();

        ['search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('order');
        if(!empty($group)){
            $where['create_group']=['=',$group];
        }

        if(!empty($search_user)) {
            $where['create_user'] = ['in', $search_user];
        }
        $where['id']=['=',$id];
        $where['del_flag']=['=',0];
        $where['order_status']=['=',1];
        $where['pay_type']=['in',[4,6]];
        $order=$OrderClass
            ->where($where)
            ->find();
        if(empty($order)){
            return json(['code'=>1,'msg'=>'未找到符合条件的账单']);
        }
        $OrderClass->startTrans();
        try {
            $result=$OrderClass->isUpdate()->save(['stock_status'=>2,'logistics_status'=>2],['id'=>$id]);
            if($result===false){
                return json(['code'=>1,'msg'=>'更新发货状态失败']);
            }
            $result=$OrderHistoryClass->isUpdate(false)->save(['order_id'=>$id,'operator'=>$this->user_session['id'],'operational'=>'发货']);
            if($result===false){
                return json(['code'=>1,'msg'=>'更新发货状态失败']);
            }

            $OrderClass->commit();
            return json(['code'=>0,'msg'=>'已发货']);
        }catch (Exception $e){
            $OrderClass->rollback();
            trace('更新发货失败'.$e->getMessage(),'error');
            return json(['code'=>1,'msg'=>'更新发货失败']);
        }
    }

    /**
     * splitInvoice
     * 拆分账单
     * @url /order/invoice/split
     * @method POST
     * @request int id 账单ID
     * @request array table 表格数据
     * @request array select 选中保留数据
     * @return Json
     * @throws \think\exception\PDOException
     * @author Asira
     * @date 2021/1/13
     */
    public function splitInvoice(): Json
    {
        $id=input('post.id');
        $table=input('post.table/a');
        $select=input('post.select/a');
        if(empty($select)){
            return json(['code'=>1,'msg'=>'请选择保留的商品']);
        }
        ['status'=>$status,'result'=>$result]=Order::updateOrderCheckData($id);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        $old_order=$result['order'];

        if($old_order['pay_type']===4){
            return json(['code'=>1,'msg'=>'不可拆分账单']);
        }

        $insert_new_order=['order_id'=>self::generateOrderId(),'pay_type'=>0,'customer_id'=>$old_order['customer_id'],'user_name'=>$old_order['user_name'],'curr_type'=>$old_order['curr_type'],'email'=>$old_order['email'],'cc_email'=>$old_order['cc_email'],'country'=>$old_order['country'],'city'=>$old_order['city'],'address'=>$old_order['address'],'zip_code'=>$old_order['zip_code'],'phone'=>$old_order['phone'],'tip'=>$old_order['tip'],'payment_type'=>$old_order['payment_type'],'partial_pay'=>$old_order['partial_pay'],'ship_fee'=>$old_order['ship_fee'], 'create_user' =>$old_order['create_user'], 'create_group' =>$old_order['create_group']];
        $update_order=[];

        $new_order=['insert'=>[],'gift_item'=>[]];
        $order=['insert'=>[],'update'=>[],'delete'=>[],'gift_item'=>[],'update_gift'=>[],'delete_gift'=>[]];
        $items_price=0;
        $new_items_price=0;
        $pro_ids=[];
        foreach ($table as $key=>$value){
            if($value['pro_id']){
                $pro_ids[]=$value['pro_id'];
            }
            if($value['delete']){
                $order['delete'][]=$value['id'];
                continue;
            }
            if (!$value['id']) {
                $arr=['order_id' => $id, 'cn_name' => $value['cn_name'], 'en_name' => $value['en_name'], 'show_index' => $key + 1, 'pro_id' => $value['pro_id'], 'amount' => $value['amount'], 'selling_price' => $value['selling_price'], 'type' => $value['type'], 'gift' => $value['gift'], 'create_user' => $value['create_user']??$this->user_session['id'],'create_group' => $value['create_group']??$this->user_session['group_id']];
                $arr['children']=$value['children']??[];
                if($value['gift']!=1) {
                    if(!in_array($key,$select,true)){
                        $new_order['insert'][] = $arr;
                        $new_items_price+=$value['selling_price'];
                    }else{
                        $order['insert'][] = $arr;
                        $items_price += $value['selling_price'];
                    }
                }else{
                    if(!in_array($key,$select,true)){
                        $new_order['gift_item'][] = $arr;
                    }else{
                        $order['gift_item'][] = $arr;
                    }
                }
            } else {
                $arr=['order_id' => $id, 'cn_name' => $value['cn_name'], 'en_name' => $value['en_name'], 'show_index' => $key + 1, 'pro_id' => $value['pro_id'], 'amount' => $value['amount'], 'selling_price' => $value['selling_price'], 'type' => $value['type'], 'gift' => $value['gift'], 'create_user' => $value['create_user']??$this->user_session['id'],'create_group' => $value['create_group']??$this->user_session['group_id'],'children'=>$value['children']??[]];
                if($value['gift']!=1) {
                    if(!in_array($key,$select,true)) {
                        $new_order['insert'][]=$arr;
                        $order['delete'][]=$value['id'];
                        $new_items_price+=$value['selling_price'];
                    }else{
                        $arr['id']=$value['id'];
                        unset($arr['create_user'],$arr['create_group']);
                        $order['update'][]=$arr;
                        $items_price += $value['selling_price'];
                    }
                }else{
                    if(!in_array($key,$select,true)) {
                        $new_order['gift_item'][]=$arr;
                        $order['delete'][]=$value['id'];
                    }else{
                        $arr['id']=$value['id'];
                        unset($arr['create_user'],$arr['create_group']);
                        $order['update_gift'][]=$arr;
                    }
                }
            }
        }

        $insert_new_order['total_price']=$new_items_price+$insert_new_order['ship_fee'];
        $insert_new_order['items_price']=$new_items_price;
        if($insert_new_order['total_price']<$insert_new_order['partial_pay']){
            $insert_new_order['partial_pay']=$insert_new_order['total_price'];
        }
        $update_order['total_price']=$items_price+$old_order['ship_fee'];
        $update_order['items_price']=$items_price;
        if($update_order['total_price']<$old_order['partial_pay']){
            $update_order['partial_pay']=$update_order['total_price'];
        }

        if(empty($new_order['insert']) || (empty($order['insert']) && empty($order['update']))){
            return json(['code'=>1,'msg'=>'账单必须包含一个商品']);
        }

        ['status'=>$status,'result'=>$result]=Order::splitInvoice($id,$order,$new_order,$update_order,$insert_new_order,$pro_ids);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        ['status'=>$status,'result'=>$stockResult]=Product::demandStockByProduct($pro_ids);
        if($status===false){
            return json(['code'=>2,'msg'=>'拆单成功，锁定需求库存失败',$stockResult]);
        }
        $result=$this->invoiceCreate($result['id']);
        $result=json_decode($result->getContent(),true);
        if($result['code']===0){
            return json(['code'=>0,'msg'=>$result['msg']]);
        }
        return json(['code'=>0,'msg'=>'拆单成功，paypal创建订单失败'.$result['msg']]);
    }

    public function createWaybill()
    {
        $ids=input('post.id/a');
        if(empty($ids)){
            return json(['code'=>1,'msg'=>'请选择订单']);
        }
        ['status'=>$status,'result'=>$result]=Waybill::createWaybill($ids);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>'运单创建成功','id'=>$result['waybill_id']]);
    }

    public function changeGoods()
    {
        $data=input('post.data/a');
        if (empty($data)){
            return json(['code'=>1,'msg'=>'请填写商品信息']);
        }
        ['status'=>$status,'result'=>$result]=OrderItem::changeGoods($data);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        $pro_id=$result['pro_id'];
        ['status' => $status, 'result' => $result] = Product::lockStockByProduct($pro_id);
        if ($status === false) {
            return json(['code' => 2, 'msg' => '修改商品成功，锁定库存失败', $result]);
        }
        ['status' => $status, 'result' => $result] = Product::demandStockByProduct([$pro_id]);
        if ($status === false) {
            return json(['code' => 2, 'msg' => '修改商品成功，锁定需求库存失败', $result]);
        }
        return json(['code'=>0,'msg'=>'修改商品成功']);
    }

    public function getGroup()
    {
        $ids=input('post.ids/a');
        $row=Db::name('customer_order')->where('id',$ids[0])->field('create_group')->find();
        return json(['code'=>0,'group'=>$row['create_group']]);
    }

    public function updateCustomer()
    {
        $ids=input('post.ids/a');
        $name=input('post.name');
        ['status'=>$status,'result'=>$result]=CustomerOrder::changeCustomer($ids,$name);
        if ($status === false) {
            return json(['code' => 1, 'msg' => $result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function orderByGoodsId()
    {
        $pro_id=input('post.id');
        $oid=input('post.oid');
        ['status'=>$status,'result'=>$result]=Order::getOrderByPro($pro_id,$oid);
        return json(['code'=>0,'data'=>$result['data']]);
    }

    public function distributionStock()
    {
        $ids=input('post.ids/a');
        $id=input('post.id');
        ['status'=>$status,'result'=>$result]=OrderItem::distributionStock($id,$ids);
        if ($status === false) {
            return json(['code' => 1, 'msg' => $result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function remarkOrder(){
        $id=input('post.id');
        $remark=input('post.remark');

        if(empty($id)){
            return json(['code'=>1,'msg'=>'id 不能为空']);
        }
        if(empty($remark)){
            return json(['code'=>1,'msg'=>'备注不能为空']);
        }

        ['status'=>$status,'result'=>$result]=Order::remarkOrder($id,$remark);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }
}